import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:speak_text/main.dart';
import 'package:speak_text/spk.dart';

class MyReader extends StatelessWidget {
  // ignore: prefer_typing_uninitialized_variables
  final BuildContext mainContext;
  MyReader({super.key, required this.mainContext}) {
    () async {
      var store = await SharedPreferences.getInstance();
      double? spd = store.getDouble('speed');
      if (spd != null) {
        Provider.of<MyData>(mainContext, listen: false).setSpeed(spd);
      }
    }();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('乱序阅读'),
      ),
      body: Center(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('速度：${Provider.of<MyData>(context).speed.toStringAsFixed(1)}'),
                Slider(
                  value: Provider.of<MyData>(context, listen: false).speed,
                  onChanged: (value) async {
                    //print('fhz: speed $speed');
                    flutterTts.setSpeechRate(value);
                    Provider.of<MyData>(context, listen: false).setSpeed(value);
                    var store = await SharedPreferences.getInstance();
                    await store.setDouble('speed', value);
                  },
                  min: 0.1,
                  max: 1.7,
                  divisions: 16,
                  label:
                      '速度:${Provider.of<MyData>(context, listen: false).speed.toStringAsFixed(1)}',
                ),
              ],
            ),
            Text(
                '序号：${Provider.of<MyData>(context).index + 1}/${Provider.of<MyData>(context, listen: false).content.length}'),
            ElevatedButton(
              onPressed: () {
                speakText(Provider.of<MyData>(context, listen: false).head());
              },
              child: const Text('第一个'),
            ),
            ElevatedButton(
              onPressed: () {
                speakText(Provider.of<MyData>(context, listen: false).next());
              },
              child: const Text('下一个'),
            ),
            ElevatedButton(
              onPressed: () {
                speakText(Provider.of<MyData>(context, listen: false).last());
              },
              child: const Text('上一个'),
            ),
            ElevatedButton(
              onPressed: () {
                speakText(Provider.of<MyData>(context, listen: false).tail());
              },
              child: const Text('最后一个'),
            ),
          ],
        ),
      ),
    );
  }
}
